package com.kehutong.crm.service.impl;

import java.util.List;

import com.kehutong.crm.enums.TagSourceType;
import com.kehutong.crm.enums.ThirdPartySource;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import com.kehutong.common.entity.Root;
import com.kehutong.crm.entity.Tag;
import com.kehutong.crm.service.TagService;

/**
 * 客户标签服务实现类
 * @author: liukunlong
 * @date: 2021-03-05 16:01
 */
@WebService("/crm/tag")
public class TagServiceImpl implements TagService {
    private static final Logger logger = LoggerFactory.getLogger(TagServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    /**
     * 根据条件获取客户标签列表
     * @param jsonObject 查询对象
     * @return 操作结果
     * @throws Exception 操作异常
     */
    @ReqMapping("/getTagList")
    public Object getTagList(JSONObject jsonObject) throws Exception {
        Page<Tag> result = null;
        if (logger.isDebugEnabled()) {
            //logger.debug("parameter:" + jsonObject);
        }
        FindPage<Tag> find = jdbcSession.findPage(Tag.class)
                .eq(jsonObject, "id", "pid")
                .eq("deleted", 0)
                .between("createTime", jsonObject, "beginTime", "endTime")
                .like(jsonObject, "name", "desc")
                .order("createTime", "DESC") ;

        Boolean group=jsonObject.getBoolean("group");
        if (Objects.nonNull(group)) {
            find.eq("group",group);
        }
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (pageSize == null) {
            jsonObject.put("pageSize",Short.MAX_VALUE);
        }
        find.page(jsonObject);

        result = find.exe();
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        return result;
    }

    /***
     * 根据客户标签标志获取客户标签信息
     * @param id 客户标签标志
     * @return 操作结果
     * @throws Exception 操作异常
     */
    @ReqMapping("/getTagById")
    public Object getTagById(String id) throws Exception {
        Tag result = null;
        if (logger.isDebugEnabled()) {
            logger.debug("parameter:" + id);
        }
        result = jdbcSession.findById(Tag.class, id);
        //若果当前标签是标签组则返回子级下面的标签
        if(result.isGroup()){
            List<Tag> tags = jdbcSession.findArray(Tag.class)
                    .eq("pid",id)
                    .eq("deleted", false)
                    .exe();
            result.setChildList(tags);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + result);
        }
        return result;
    }


    /**
     * 保存客户标签
     *
     * @param tag 客户标签对象
     * @return 操作结果
     * @throws Exception 操作异常
     */
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/saveTag")
    public Object saveTag(Tag tag) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("parameter:" + tag);
        }
        List<Tag> exe = jdbcSession.findArray(Tag.class)
                .eq("pid", tag.getPid())
                .eq("name", tag.getName())
                .eq("deleted", false).exe();
        if (exe.size() != 0) {
            return Result.error(1, "该标签名已存在！");
        }
        //标签的父id是根节点则为标签组
        tag.setGroup(Root.isRoot(tag.getPid()));
        tag.setCreateBy(tag.getCreateBy());
        tag.setCreateName(tag.getCreateName());
        tag.setThirdPartySource(ThirdPartySource.WEIXIN);
        tag.setType(TagSourceType.THIRD_PARTY_TAG);
        tag.setSort(System.currentTimeMillis());
        jdbcSession.insert(tag);
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + tag);
        }
        return Result.success(tag);
    }
    /**
     * 更新客户标签
     *
     * @param tag 客户标签对象
     * @return 操作结果
     * @throws Exception 操作异常
     */
    @Bean(copy = true)
    @ReqMapping("/updateTag")
    public Object updateTag(Tag tag) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("parameter:" + tag);
        }
        if (Objects.isEmpty(tag.getId()) ) {
            return Result.error(1, "标签标志不能为空！");
        }

        //数据库中的标签
        Tag dbTag = Pool.get(Tag.class, tag.getId());
        if (Objects.isNull(dbTag)) {
            return Result.error(2, "该标签不存在！");
        }

        //如果更新的标签名称与数据库已有标签名称不一致
        if (!tag.getName().equals(dbTag.getName())) {
            //校验标签组下面有重复的标签名称
            List<Tag> exe = jdbcSession.findArray(Tag.class)
                    .eq("pid", tag.getPid())
                    .eq("name", tag.getName())
                    .eq("deleted", false).exe();
            if (exe.size() != 0) {
                return Result.error(-1, "该标签名已存在当前标签组下面！");
            }
            //todo 后续可以加入同步标签到腾讯服务器
            /*JSONObject rs=doveClient.post("/wwin-service/tag/wwin/update",(http)-> {
                http.addHeader("companyNo", token.getCompanyNo());
                http.setBody(JSONObject.toJSONString(syncTagGroup(resultTag)));
            });*/
        }
        //标签的父id是根节点则为标签组
        tag.setGroup(Root.isRoot(tag.getPid()));
        tag.setCreateBy(tag.getCreateBy());
        tag.setCreateName(tag.getCreateName());
        tag.setSort(System.currentTimeMillis());
        jdbcSession.updateById(tag);
        if (logger.isDebugEnabled()) {
            logger.debug("result:" + tag);
        }
        return Result.success(tag);
    }


    /***
     * 根据客户标签标志删除客户标签信息
     * 标签在数据库中一共有2级,第一级为标签组,第二级为标签，可以通过pid是否是根节点判断是否是标签组
     * @param id 客户标签标志
     * @return 操作结果
     * @throws Exception 操作异常
     */
    @ReqMapping("/deleteTagById")
    public Object deleteTagById(String id) throws Exception {
        boolean flag = false;
        if (logger.isDebugEnabled()) {
            logger.debug("parameter:" + id);
        }
        if (!Objects.isEmpty(id)) {
            Tag tag = Pool.get(Tag.class, id);
            //如果当前标签是标签组则删除标签组及标签组下面的子标签
            if (Root.isRoot(tag.getPid())) {
                //删除标签组
                jdbcSession.deleteById(tag);
                //删除标签组下面的子标签
                List<Tag> list = jdbcSession.findArray(Tag.class)
                        .eq("pid", tag.getId())
                        .eq("deleted", false)
                        .exe();
                jdbcSession.deleteById(list);
                flag=true;
            }else {
                jdbcSession.deleteById(tag);
                flag=true;
            }

        }
        return Result.success(flag);
    }

}
